package 笔试;

import java.math.BigDecimal;
import java.util.Objects;
import java.util.Random;

public class RedPackThreadTest {
    static class RedPack {
        BigDecimal totalAmount;//总钱数
        int amount;//总钱数,单位分
        int redPackCount;//红包总数

        public RedPack(BigDecimal totalAmount, int redPackCount) {
            this.totalAmount = totalAmount;
            this.amount = totalAmount.multiply(new BigDecimal("100")).intValue();
            this.redPackCount = redPackCount;
        }

        public synchronized BigDecimal getRandomMoney() {
            int val;//每个人分配到的金额*100
            //当剩下的人只分到一分钱的时候
            if (redPackCount != 0 && amount / redPackCount == 1) {
                val = 1;
                amount = amount - val;
                redPackCount--;
                return new BigDecimal(String.valueOf(val)).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_UP);
            }

            if (redPackCount <= 0) {
                val = 0;
            } else if (redPackCount == 1) {
                val = amount;//如果是最后一个
            } else {
                BigDecimal leftAmount; //剩下的金额
                while (true) {
                    // 随机生成当前金额的随机数 [0,totalVal/count-1),尽量平均一点
                    val = new Random().nextInt(amount / redPackCount * 2);
                    leftAmount = new BigDecimal(amount + "").subtract(new BigDecimal(val + ""));
                    // 判断生成的金额大于0，且剩余的钱数够剩下人平分到0.01元
                    if (leftAmount.divide(new BigDecimal(redPackCount - 1), 0, BigDecimal.ROUND_UP).intValue() >= 1 && val > 0) {
                        break;
                    }
                }
                amount = amount - val;
            }
            redPackCount--;
            return new BigDecimal(String.valueOf(val)).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_UP);
        }
    }

    static class UserThread implements Runnable {
        private RedPack redPack;

        public UserThread(RedPack redPack) {
            this.redPack = redPack;
        }

        @Override
        public void run() {
            BigDecimal money = redPack.getRandomMoney();
            if (money.compareTo(BigDecimal.ZERO) == 0) {
//                System.out.println(Thread.currentThread().getName() + "红包已抢完--");
            } else {
                System.out.println(Thread.currentThread().getName() + "抢到 " + money + "元");
            }
        }
    }

    public static void main(String[] args) {
        RedPack redPack = new RedPack(new BigDecimal("100"), 10);
        UserThread userThread = new UserThread(redPack);

        for (int i = 0; i < 100; i++) {
            new Thread(userThread).start();
        }
    }
}